package fileAndIO;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Downloader {
    private int threadNum = 10;

    public void download(String source, String targetDir) {
        InputStream is = null;
        OutputStream os = null;
        try {
            String fileName = source.substring(source.lastIndexOf("/") + 1);
            File targetFile = new File(targetDir + "/" + fileName);
            URL url = new URL(source);
            URLConnection connection = url.openConnection();
            is = connection.getInputStream();
            os = new FileOutputStream(targetFile);
            byte[] bs = new byte[1024];
            int len = 0;
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            System.out.println("[INFO]图片下载完毕:" + source + "\n\t  ->" + targetFile.getPath() + "(" + Math.floor(targetFile.length() / 1024) + "kb)");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public void multiDownloadFromFile(String targetDir, String downloadText) {
        File dir = new File(targetDir);
        if (!dir.exists()) {
            dir.mkdirs();
            System.out.println("[INFO]发现下载目录：[" + targetDir + "不存在，已自动创建");
        }
        List<String> resources = new ArrayList<>();
        BufferedReader reader = null;
        ExecutorService threadPool = null;
        try {
            reader = new BufferedReader(new FileReader(downloadText));
            String line = null;
            while ((line = reader.readLine()) != null) {
                resources.add(line);
                System.out.println(line);
            }
            threadPool = Executors.newFixedThreadPool(this.threadNum);
            Downloader that = this;
            for (String resource : resources) {
                threadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        that.download(resource, targetDir);
                    }
                });
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (threadPool != null) {
                threadPool.shutdown();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public void start(String propDir) {
        File propFile = new File(propDir + "\\config.properties");
        Properties properties = new Properties();
        FileReader reader = null;
        try {
            reader = new FileReader(propFile);
            properties.load(reader);
            this.threadNum = Integer.parseInt(properties.getProperty("thread-num"));
            String targetDir = properties.getProperty("target-dir");
            this.multiDownloadFromFile(targetDir, propDir + "\\download.txt");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public static void main(String[] args) {
        Downloader downloader = new Downloader();
        downloader.start("C:\\Users\\83726\\IdeaProjects\\Java-learn\\src");
    }
}
